﻿using System.Collections;
using com.guojin.mj.net;
using com.guojin.mj.net.message.login;
using UnityEngine;
using UnityEngine.UI;
using DG.Tweening;

public class LoginPage : EventManager
{
    public Button wxLoginBtn,AccountLogin;
    public Button visitorLoginBtn;
    public Toggle agreeTog;
    public Button agreeBtn;
    public InputField ZCAccut,ZCPassword,Code,LoginAccount,LoginPassword;
    public Button ZCRet;
    public Text YZAccu;
    public Button ForgetNext,ForgetSend;
    public InputField ForgetPhone,FoegetCode,ForgetPassword;
    public Text Forgetphone;
    public override void InformationSetting()
    {
        //PlayerPrefs.DeleteAll();

        SetActive(this.BindingSource[6],false);
        SetActive(this.BindingSource[7], true);
        LoginAccount.text = PlayerPrefs.GetString("LoginAccount", "");
        LoginPassword.text = PlayerPrefs.GetString("LoginPassword", "");

        //#if UNITY_ANDROID && !UNITY_EDITOR
        //        LoginAndShare.Controller.GetRoomNoFromAD();
        //#elif UNITY_IPHONE
        //#endif
        TestNetworkConnected();
    }

    void Start()
    {
        AddListenerToButton(wxLoginBtn, wxLoginBtnClick);
        AddListenerToButton(visitorLoginBtn, VisitorLoginBtnClick);
        AddListenerToButton(agreeBtn, agreeBtnClick);
        AddListenerToButton(ZCRet, SenYanZhengRet);
        AddListenerToButton(AccountLogin, Accountlogin);
        AddListenerToButton(ForgetSend, ForgetSendMsg);
        Open();
    }
    
    void TestNetworkConnected()
    {
        //判断网络的连通性
        if (Application.internetReachability == NetworkReachability.NotReachable)
        {
            TooL.ShowTipsPage("无法连接网络！请打开wifi或4G网络后重试。", TooL.TipsPageType.noCancelPage, () =>
            {
                TestNetworkConnected();
            });
        }
        else
        {
            StartConnectSever();
        }
    }

    private void StartConnectSever()
    {
        StartCoroutine(ConnectSever());
        StartCoroutine(StartCheckToken());
    }

    IEnumerator ConnectSever()
    {
        if (!SocketMgr.GetInstance().isNetOpen)
        {
            SocketMgr.GetInstance().InitNet();
            yield return new WaitForSeconds(6f);
            StartCoroutine(ConnectSever());
        }
    }

    IEnumerator StartCheckToken()
    {
        yield return new WaitUntil(() => SocketMgr.GetInstance().isNetOpen);
        StopAllCoroutines();
        SetActive(this.BindingSource[7], false);
        CheckToken();
    }

    public bool wxLogin = false;
    /// <summary>
    /// 开始自动登录，判断使用token登录还是wx登录
    /// </summary>
    void CheckToken()
    {
        //PlayerPrefs.DeleteAll();                  //匿名登录删除token
        if (SocketMgr.GetInstance().isNetOpen)
        {

            string token = PlayerPrefs.GetString(DefaultKeyConst.VisitorTokenKey,"");
            //string token = "9c1d2966-80d7-4274-997e-296d5b5d586f";
            if (!token.Equals(""))
            {

                string longitude = GameData.GetInstance().longitude;        //启动游戏时由jar包中调用获取方法
                string latitude = GameData.GetInstance().latitude;
                Debug.Log("longitude>>" + longitude + "  latitude>>" + latitude);
                MessageManager.GetInstance().SendMsg78("TOKEN", token, null, longitude, latitude);
                StartCoroutine(TokenUselessCallWx());                               //1.5s内没反应说明token失效再次吊起微信登录
            }
            else
            {
                if (wxLogin)
                {

                    wxLogin = false;
#if UNITY_EDITOR || ANONYMOUS
                    MessageManager.GetInstance().SendMsg78("ANONYMOUS", null, null, "34.7545", null);
#elif WX_SDK
                    //LoginAndShare.Controller.OnClickWXLogin();
#endif
                }
                else
                {

                    //MessageManager.GetInstance().SendMsg78("ANONYMOUS", null, null, "34.7545", null);

                    wxLoginBtn.gameObject.SetActive(true);
                }
            }
        }
        else
        {

            StartConnectSever();
        }
    }

    //token无效时是否允许吊起微信（token登录后，1.5秒无反应如果允许就吊起微信登录）
    public bool IsNeedWxPutOn = true;
    public IEnumerator TokenUselessCallWx()
    {
        yield return new WaitForSeconds(4f);
#if UNITY_EDITOR
        MessageManager.GetInstance().SendMsg78("ANONYMOUS", null, null, "34.7545", null);
#else
        if (IsNeedWxPutOn)
        {
            //LoginAndShare.Controller.OnClickWXLogin();
        }
#endif
    }

    void wxLoginBtnClick()
    {
        print("locing——————————");

        if (Application.internetReachability == NetworkReachability.NotReachable)
        {
            TooL.ShowTipsPage("无法连接网络！请打开wifi或4G网络后重试。", TooL.TipsPageType.noCancelPage, () =>
            {
                TestNetworkConnected();
            });
        }
        else
        {
            Debug.Log("wxLoginBtnClick");

            if (agreeTog.GetComponent<Toggle>().isOn)
            {
                if (isWXLoginBtnClick == true)
                {
                    isWXLoginBtnClick = false;

#if UNITY_EDITOR || ANONYMOUS    //这里注意是匿名登录/* || UNITY_ANDROID  
                    MessageManager.GetInstance().SendMsg78("ANONYMOUS", null, null, "34.7545", null);
#elif WX_SDK
                    string token = PlayerPrefs.GetString(DefaultKeyConst.VisitorTokenKey);
                    if (!token.Equals(""))
                    {
                        string longitude = GameData.GetInstance().longitude;        //启动游戏时由jar包中调用获取方法
                        string latitude = GameData.GetInstance().latitude;
                        Debug.Log("longitude>>" + longitude + "  latitude>>" + latitude);
                        MessageManager.GetInstance().SendMsg78("TOKEN", token, null, longitude, latitude);
                        StartCoroutine(TokenUselessCallWx());                               //1.5s内没反应说明token失效再次吊起微信登录
                    }
                    else
                    {
                        LoginAndShare.Controller.OnClickWXLogin();
                    }
#endif
                }
            }
            else
            {
                TooL.ShowTipsPage("请勾选同意用户协议\n感谢您的配合，祝您游戏愉快!",TooL.TipsPageType.noCancelPage, () => { agreeTog.GetComponent<Toggle>().isOn = true; });
            }
        }
    }
    void VisitorLoginBtnClick()
    {
        print("locing——————————");

        //PlayerPrefs.DeleteAll();
        string token = PlayerPrefs.GetString(DefaultKeyConst.VisitorTokenKey);                //这里写token可以用提供的token登录
        //string token = "9c52b253-08d1-4087-be54-ccc590616044";
        string longitude = GameData.GetInstance().longitude;
        string latitude = GameData.GetInstance().latitude;
        if (!token.Equals(""))
        {
            MessageManager.GetInstance().SendMsg78("TOKEN", token, null, longitude, latitude);
        }
        else
        {
            MessageManager.GetInstance().SendMsg78("ANONYMOUS", null, null, longitude, latitude);
        }
    }
    void agreeBtnClick()
    {
        UIManager.ChangeUI(UIManager.PageState.UserAgreeMentPage, (GameObject obj) =>
        {
            obj.GetComponent<UserAgreeMentPage>().InformationSetting();
        });
    }
    bool isWXLoginBtnClick = true;
    float timer = 0;
    void Update()
    {
        if (!isWXLoginBtnClick)
        {
            timer += Time.deltaTime;
            if (timer > 3)
            {
                timer = 0;
                isWXLoginBtnClick = true;
            }
        }
    }
   public void Register() {
        BindingSource[0].transform.DOLocalMoveX(0f, 0.6f);
    }
    void ForGet()
    {
        BindingSource[1].transform.DOLocalMoveX(0f, 0.6f);
    }
   public  void RegisterRet()
    {
        BindingSource[0].transform.DOLocalMoveX(1381f, 0.6f);
    }
    void ForGetRet()
    {
        BindingSource[1].transform.DOLocalMoveX(1381f, 0.6f);
    }
    void ForGetNext()
    {
        if (ForgetPhone.text != null && ForgetPhone.text != "")
        {
            MessageManager.GetInstance().Send7151(ForgetPhone.text);
        }
        else
        {
            TooL.WenXinTiSi("请输入您的账号");
            return;
        }
        Forgetphone.text = ForgetPhone.text;
        BindingSource[4].transform.DOLocalMoveX(0f, 0.6f);
    }
    void ForGetNextRet()
    {
        BindingSource[4].transform.DOLocalMoveX(1381f, 0.6f);
    }
    public void Go() {
        LoginController.GetInstance().Go();
    }
    void ZcNect() {
        if (ZCAccut.text==null|| ZCAccut.text==""||ZCPassword.text==""||ZCPassword.text==null)
        {
            TooL.WenXinTiSi("账号和密码不能为空");
            return;
        }
        if (ZCAccut.text.Length!=11)
        {
            TooL.WenXinTiSi("账号长度不符合");
            return;
        }
        if (ZCPassword.text.Length > 12|| ZCPassword.text.Length<4)
        {
            TooL.WenXinTiSi("密码长度必须为4-12位");
            return;
        }
        if (GetPassword(ZCPassword.text))
        {
            Debug.Log("可以继续注册");
            GameObject ts = Instantiate(Resources.Load("Prefab/TiSi/ZuCeTiSi")) as GameObject;
            ts.transform.SetParent(GameObject.Find("addNode").transform);
            ts.transform.localScale = Vector3.one;
            ts.transform.localPosition = Vector3.zero;
            ts.GetComponent<TiSiZuCe>().Setnumber(ZCAccut.text, ZCPassword.text);
        }
        else
        {
            TooL.WenXinTiSi("密码必须包含数字和字母");
        }
    }
    bool GetPassword(string pas) {
        int Zm = 0;
        int Shu = 0;
        for (int i = 0; i < pas.Length; i++)
        {
            byte temp = System.Convert.ToByte(pas[i]);
            if (temp <= 122 && temp >= 65)
                Zm = 1;
            if (temp <= 57 && temp >= 48)
                Shu = 1;
        }
        if (Zm == 1 && Shu == 1)
            return true;
        else
        {
            return false;
        }
    }
    public void SenYanZheng() {
        BindingSource[5].transform.DOLocalMoveX(0f, 0.6f);
        YZAccu.text = ZCAccut.text;
    }
    public void SenYanZhengRet()
    {
        BindingSource[5].transform.DOLocalMoveX(1381f, 0.6f);
    }
    void ZCTiJiao() {
        if (Code.text!=null&& Code.text!="")
        {
            MessageManager.GetInstance().Send7146(ZCAccut.text, Code.text);
        }
    }
    void Accountlogin() {
        if (LoginAccount.text!=""&& LoginAccount.text!=""&& LoginPassword.text!=null&& LoginPassword.text!="")
        {
            MessageManager.GetInstance().Send7149(LoginAccount.text, LoginPassword.text);
            PlayerPrefs.SetString("LoginAccount", LoginAccount.text);
            PlayerPrefs.SetString("LoginPassword", LoginPassword.text);
            PlayerPrefs.Save();
        }
        else
        {
            TooL.WenXinTiSi("账户和密码不能为空");
        }
    }
    void ForgetSendMsg() {
        if (FoegetCode.text == null || FoegetCode.text == "" || ForgetPassword.text == "" || ForgetPassword.text == null)
        {
            TooL.WenXinTiSi("验证码和密码不能为空");
            return;
        }
        if (FoegetCode.text.Length > 12 || FoegetCode.text.Length < 4)
        {
            TooL.WenXinTiSi("密码长度必须为4-12位");
            return;
        }
        if (GetPassword(ForgetPassword.text))
        {
            Debug.Log("可以继续注册");
            MessageManager.GetInstance().Send7153(ForgetPhone.text, FoegetCode.text, ForgetPassword.text);
        }
        else
        {
            TooL.WenXinTiSi("密码必须包含数字和字母");
        }
    }
}